package com.example.cookieshop.controller;

import com.example.cookieshop.common.AjaxResult;
import com.example.cookieshop.common.GlobalVariable;
import com.example.cookieshop.common.PasswordUtils;
import com.example.cookieshop.entity.User;
import com.example.cookieshop.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 登录
     *
     * @param request
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public AjaxResult login(HttpServletRequest request, String username, String password) {
        if (!StringUtils.isEmpty(username) || !StringUtils.isEmpty(password)) {
            return AjaxResult.fail(-1, "非法的请求");
        }
        User user = userService.login(username, password);
        if (user != null && user.getId() >= 0) {
            if (PasswordUtils.check(password, user.getPassword())) {
                HttpSession session = request.getSession();
                session.setAttribute(GlobalVariable.USER_SESSION_KEY, user);
                System.out.println("登录成功!");
                user.setAddress("");
                return AjaxResult.success(user);
            }
        }
        System.out.println("登录失败!");
        return AjaxResult.fail(-1, "无效用户,登录失败!");
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public AjaxResult register(User user) {
        if (!StringUtils.hasLength(user.getUsername()) || !StringUtils.hasLength(user.getPassword())) {
            return AjaxResult.fail(-1, "无效参数");
        }
        System.out.println(user.toString());
        user.setPassword(PasswordUtils.encrypt(user.getPassword()));
        return AjaxResult.success(userService.register(user));
    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute(GlobalVariable.USER_SESSION_KEY);
        return AjaxResult.success(1);
    }

    /**
     * 修改个人信息
     *
     * @param user
     * @return
     */
    @RequestMapping("/update")
    public AjaxResult update(User user) {
        if (user == null || user.getId() < 0) {
            return AjaxResult.fail(-1, "无效参数");
        }
        return AjaxResult.success(userService.update(user));
    }
}
